package com.eliauk.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.eliauk.demo.entity.User;
import com.eliauk.demo.service.IUserService;
import com.eliauk.demo.service.impl.UserServiceImpl;
import com.eliauk.demo.utils.excel.converter.DateConverter;
import com.eliauk.demo.utils.excel.listener.UserListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class ExcelController {

    @Autowired
    private IUserService userService;

    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), User.class, new UserListener(new UserServiceImpl()))
                .sheet()
                .registerConverter(new DateConverter())//读excel文件时加上一个日期转换器
                .doRead();
        return "success";
    }


    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("模板")
                .doWrite(userService.list());
    }



}
